<template>
  <div class="share">
    <el-card class="box-card">
      <div slot="header"
           class="clearfix">
        <el-link @click="isTGShow = true"
                 type="primary"
                 style="float: right; padding: 3px 0"
                 :underline="false">推广说明</el-link>
      </div>
      <el-form class="demo-form-inline">
        <el-form-item>
          <el-row>
            <el-col :xs="24"
                    :sm="8"
                    :md="8"
                    :lg="8"
                    :xl="8">
              累计收益：<el-link type="danger"
                       :underline="false">{{
                                    (syAndMony.count_yield / 100).toFixed(2)
                                }}&nbsp;元</el-link>
            </el-col>
            <el-col :xs="24"
                    class="links"
                    :sm="16"
                    :md="16"
                    :lg="16"
                    :xl="16">
              推广链接地址 :&nbsp;
              <el-link type="warning"
                       class="linkss"
                       :underline="false">
                {{ url }} </el-link>&nbsp;
              <el-button type="primary"
                         v-clipboard:copy="url"
                         v-clipboard:success="onCopy"
                         v-clipboard:error="onError"
                         size="small">点击复制</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row>
            <el-col :xs="24"
                    :sm="8"
                    :md="8"
                    :lg="8"
                    :xl="8">
              可提现佣金：<el-link type="danger"
                       :underline="false">{{
                                    (syAndMony.can_by_money / 100).toFixed(2)
                                }}&nbsp;元</el-link>&nbsp;<el-button size="small"
                         type="primary"
                         @click="isTXshow = !isTXshow">提现</el-button>
            </el-col>
            <el-col :xs="24"
                    :sm="16"
                    :md="16"
                    :lg="16"
                    :xl="16">
              专属二维码海报：
              <el-link @click="dialogVisible = !dialogVisible"
                       :underline="false"
                       type="primary">选择我的专属海报</el-link>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <el-tabs v-model="activeName"
               @tab-click="handleClick">
        <el-tab-pane label="邀请记录"
                     name="first">
          <el-table :data="yqjl"
                    style="width: 100%">
            <el-table-column prop="create_time"
                             label="注册时间">
            </el-table-column>
            <el-table-column prop="mobile"
                             label="用户名">
            </el-table-column>
            <el-table-column prop="spread_level"
                             label="等级">
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="邀请收益记录"
                     name="second">
          <el-table :data="syjl"
                    style="width: 100%">
            <el-table-column prop="source_phone"
                             label="用户名">
            </el-table-column>
            <el-table-column prop="order_type"
                             label="订单类型">
            </el-table-column>
            <el-table-column prop="profit_money"
                             label="提成">
            </el-table-column>
            <el-table-column prop="create_time"
                             label="订单时间">
            </el-table-column>
            <el-table-column prop="source_class"
                             label="二级分销">
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="提现记录"
                     name="third">
          <el-table :data="txjl"
                    style="width: 100%">
            <el-table-column prop="create_time"
                             label="全部">
            </el-table-column>
            <!-- <el-table-column prop="audited" label="待审核">
                            <template slot-scope="scope">
                                {{ scope.row.audited == 0 ? "" : "√" }}
                            </template>
                        </el-table-column> -->
            <el-table-column prop="payment"
                             label="待付款">
              <template slot-scope="scope">
                {{ scope.row.payment == 0 ? "" : "√" }}
              </template>
            </el-table-column>
            <el-table-column prop="fight_money"
                             label="已打款">
              <template slot-scope="scope">
                {{ scope.row.fight_money == 0 ? "" : "√" }}
              </template>
            </el-table-column>
            <el-table-column prop="invalid"
                             label="无效">
              <template slot-scope="scope">
                {{ scope.row.invalid == "Y" ? "有效" : "无效" }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog :visible.sync="dialogVisible"
               width="320px"
               :close-on-click-modal="false">
      <dl class="download"
          ref="down">
        <dt><img :src="qrcode"
               alt="" /></dt>
        <dd>
          <el-button :disabled="isDisabled"
                     @click="download"
                     style="width:100%;height:100%;padding:0;display:flex;align-items:center;justify-content: center;border:none;background:none;">下载到本地</el-button>
        </dd>
      </dl>
    </el-dialog>
    <el-dialog :visible.sync="isTXshow">
      <el-form :model="ruleForm"
               status-icon
               :rules="rules"
               ref="ruleForm"
               label-width="100px"
               class="demo-ruleForm">
        <el-form-item label="可提现金额"
                      prop="je">
          <el-link type="danger"
                   :underline="false">{{
                            (syAndMony.can_by_money / 100).toFixed(2)
                        }}元</el-link>
        </el-form-item>
        <el-form-item label="提现金额"
                      prop="je">
          <el-input v-model="ruleForm.je"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名"
                      prop="name">
          <el-input v-model="ruleForm.name"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="支付宝"
                      prop="zfb">
          <el-input v-model="ruleForm.zfb"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          {{ userInfo.mobile | filterMobile }}
          <span>
            <el-button style="margin-left: 30px;"
                       @click="getYZM"
                       v-if="isYZMShow"
                       type="primary"
                       size="small">获取验证码</el-button>
            <el-button v-else
                       type="primary"
                       disabled
                       size="small">{{ time }}s</el-button>
          </span>
        </el-form-item>

        <el-form-item label="手机验证码"
                      prop="yzm">
          <el-input v-model="ruleForm.yzm"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="submitForm('ruleForm')">
            申请提现
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="推广说明"
               :visible.sync="isTGShow"
               width="350px">
      <tg :tgsm="tgsm"></tg>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="isTGShow = false">取 消</el-button>
        <el-button type="primary"
                   @click="isTGShow = false">确 定</el-button>
      </span>
    </el-dialog>
    <clientBtn></clientBtn>
  </div>
</template>

<script>
import qrcode from "@/assets/images/qrcode.png";
import html2canvas from 'html2canvas';
import tg from "./components/text";
import clientBtn from '../../components/clientBtn'
export default {
  components: {
    tg,
    clientBtn
  },
  data () {
    var je = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入提现金额!'));
      } else {
        callback();
      }
    };
    var name = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入姓名!'));
      } else {
        callback();
      }
    };
    var zfb = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入支付宝!'));
      } else {
        callback();
      }
    };
    var yzm = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码!'));
      } else {
        callback();
      }
    };
    return {
      tgsm: "",
      isTGShow: false,
      isYZMShow: true,
      time: 60,
      key: "",
      syAndMony: {
        count_yield: '',
        can_by_money: '',
      },
      ruleForm: {
        je: "",
        name: "",
        zfb: "",
        sjh: "",
        yzm: ""
      },
      rules: {
        je: [
          { validator: je, trigger: 'blur' }
        ],
        name: [
          { validator: name, trigger: 'blur' }
        ],
        zfb: [
          { validator: zfb, trigger: 'blur' }
        ],
        yzm: [
          { validator: yzm, trigger: 'blur' }
        ]
      },
      qrcode,
      userInfo: {}, // 用户个人信息，包括手机号等
      isDisabled: false,
      url: "",
      isTXshow: false,
      dialogVisible: false,
      activeName: 'second',
      yqjl: [
        {
          date: "",
          name: "",
          ejfx: ""
        }
      ],
      syjl: [
        {
          date: "",
          name: "",
          ejfx: "",
          type: "",
          tc: ""
        }
      ],
      txjl: [
        {
          date: "",
          dsh: "√",
          dfk: "-",
          ydk: "-",
          wx: "-"
        }
      ]
    }
  },
  filters: {
    // 将手机号中间4位替换为*号
    filterMobile (mobile) {
      let tel = "" + mobile;
      let reg = /(\d{3})\d{4}(\d{4})/;
      return tel.replace(reg, "$1****$2")
    }
  },
  created () {
    if (localStorage.getItem("key")) {
      this.key = JSON.parse(localStorage.getItem("key"))
    }
    this.getUserInfo();
  },
  mounted () {
    _MEIQIA('hidePanel');
  },
  methods: {
    // 提现
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$ajax.post(`/spread/insextracthistory?userid=${this.userInfo.userId}`)
            .then(res => {
              this.userInfo = res.data.data;
              this.init();
            })
          console.log(1);
        } else {
          console.log(2);
          return false;
        }
      })
    },
    // 获取用户信息
    getUserInfo () {
      this.$ajax.post("/user/getInfo")
        .then(res => {
          this.userInfo = res.data.data;
          this.init();
        })
    },
    // 获取相关信息
    init () {
      this.getMoney();
      this.getLink();
      this.getCode();
      this.getmyteam();
      this.getprofithistory();
      this.getextracthistory();
      this.getspreadexplain();
    },
    showDownload () {
      this.dialogVisible = true;
    },
    getspreadexplain () { // 获取累计收益和可提现佣金
      this.$ajax.get(`/spread/getspreadexplain?userid=${this.userInfo.userId}`)
        .then(res => {
          if (res.data.code == 0) {

            this.tgsm = res.data.data
          } else {
            this.$message.error(res.data.msg)
          }


        })
    },
    getMoney () { // 获取累计收益和可提现佣金
      this.$ajax.get(`/spread/extractcash?userid=${this.userInfo.userId}`)
        .then(res => {
          if (res.data.code == 0) {
            if (res.data.data) this.syAndMony = res.data.data;

          } else {
            this.$message.error(res.data.msg)
          }
        })
    },
    getLink () { // 获取推广链接 
      this.$ajax.get(`/spread/queryLink?userid=${this.userInfo.userId}`)
        .then(res => {
          if (res.data.code == 0) {
            this.url = res.data.data
          } else {
            this.$message.error(res.data.msg)
          }
        })
    },
    getCode () { // 获取二维码
      this.$ajax.get(`/spread/qrcode?userid=${this.userInfo.userId}`)
        .then(res => {
          // this.qrcode = res.data;
          if (res.data.code == 0) {
            this.qrcode = res.data.data
          } else {
            this.$message.error(res.data.msg)
          }
        })
    },
    getmyteam () { // 获取邀请记录
      this.$ajax.get(`/spread/myteam?userid=${this.userInfo.userId}`)
        .then(res => {

          if (res.data.code == 0) {
            res.data.data.up.forEach(ele => ele.mobile = ele.mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2"));
            res.data.data.upup.forEach(ele => ele.mobile = ele.mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2"));
            var newArr = [...res.data.data.up, ...res.data.data.upup]
            this.yqjl = newArr;

          } else {
            this.$message.error(res.data.msg)
          }
        })
    },
    getprofithistory () { // 获取邀请收益记录
      this.$ajax.get(`/spread/profithistory?userid=${this.userInfo.userId}`)
        .then(res => {
          if (res.data.code == 0) {
            // 将分单位的金额，转为元
            res.data.data.map((val) => {
              val.source_phone = this.$options.filters['filterMobile'](val.source_phone)
              return val.profit_money = (val.profit_money / 100).toFixed(2);
            })
            this.syjl = res.data.data;

          } else {
            this.$message.error(res.data.msg)
          }
        })

    },
    getextracthistory () { // 获取提现记录
      this.$ajax.get(`/spread/extracthistory?userid=${this.userInfo.userId}`)
        .then(res => {
          if (res.data.code == 0) {
            this.txjl = res.data.data;
          } else {
            this.$message.error(res.data.msg)
          }
        })

    },
    onCopy: function (e) {
      alert('复制成功: ' + e.text)
    },
    onError: function (e) {
      alert('复制失败')
    },
    handleClick (tab, event) {
      console.log(tab, event);
    },
    handleClose () {

    },
    postYZM () {
      this.$ajax.post("/user/sendMobileCode", {
        type: 0,
        mobile: this.ruleForm.sjh
      })
        .then((res) => {

          if (res.data.code == 0) {
            this.$message({
              message: '验证码发送成功!',
              type: 'success'
            });
            // window.location.href = "register-bus-step02.html";
          } else[
            this.$message.error(res.data.msg)
          ]
        })
    },
    getYZM () {
      this.postYZM(); // 向后台请求数据
      this.isYZMShow = !this.isYZMShow;
      let i = 60;
      var timer = setInterval(() => {
        i--;
        if (i == 0) {
          this.isYZMShow = !this.isYZMShow;
          clearInterval(timer);
          i = 60;
        } else {
          this.time = i;
        }

      }, 1000)
    },
    download () {
      this.isDisabled = true;
      var _this = this;
      this.$message({
        type: "warning",
        message: '生成图片比较耗时,稍等片刻即可!',
      })
      html2canvas(this.$refs.down).then(function (canvas) {
        var imgUri = canvas.toDataURL("image/png");

        var alink = document.createElement("a");
        alink.href = imgUri;
        alink.download = imgUri; //图片名
        alink.click();
        _this.isDisabled = false;
        _this.dialogVisible = false;
        //window.location.href= imgUri // 下载图片       
      });

    }
  }
}
</script>
<style lang="scss" >
.links {
  .linkss {
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    span {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
</style>
<style lang="scss" scoped>
.share {
  // background: #fff;
  // padding: 18px 20px;
}
.download {
  border: 10px solid #fff4b4;
  border-bottom: 0;
  margin: 0 auto;
  dt {
    padding: 10px;
  }
  img {
    width: 90%;
    display: block;
    margin: 0 auto;
  }
  dd {
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff4b4;
    cursor: pointer;
  }
}
</style>